package com.demo1217;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet("/demo1217/login.do")
public class CookieLoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        PrintWriter writer = resp.getWriter();
        if ("admin".equals(username) && "123".equals(password)) {
            Cookie[] cookies = req.getCookies();
            String username1 = fingCookie("username", cookies);
            String password1 = fingCookie("password", cookies);
            if (username1 == null || username1.isEmpty()) {
                Cookie usernameCookie = new Cookie("username", username);
                Cookie passwordCookie = new Cookie("password", password);
                usernameCookie.setMaxAge(60*60);
                passwordCookie.setMaxAge(60*60);
                resp.addCookie(usernameCookie);
                resp.addCookie(passwordCookie);
            }
            writer.write("<h1>登录成功！</h1>");
        }
        else {
            writer.write("<h1>登录失败！</h1>");
        }
    }

    private String fingCookie(String name, Cookie[] cookies) {
        if (name == null || name.isEmpty() || cookies.length == 0) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName() == name) {
                return cookie.getValue();
            }
        }
        return null;
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
